<?php
//-------------------------------
//  Class file for use accounts
//-------------------------------
//require_once($_SERVER['DOCUMENT_ROOT'].'/include/database2.inc.php');




//------------------------
// Start class
//------------------------

//class AccountAuthenticator {
class UserAccount {

	public $error_string = "";
	public $user_r = array();

	//public $username = "";
	//public $enc_password = "";

	private $authenticated_user = "";

	// Constructor.
	//function UserAccount() {
	function __construct() {
		global $dbobj;

		// Initialize public vars.
		//$this->user_r = array();
		
		$temp = explode(" ", $_COOKIE["user"]);
		$this->cookie_username = $temp[0];
		$this->cookie_password = $temp[1];

		// Get user record.
		if ($this->cookie_username != "") {
			$user_ar = $dbobj->GetResultsAsNestedArray("SELECT * FROM mr_useraccount WHERE username = " . ValToSQL_str($this->cookie_username), 1);
			$this->user_r = $user_ar[0];

			// Compare supplied & stored passwords.
			if ($this->cookie_password == $this->user_r['password']) {
				//setcookie("user", $this->cookie_username . " " . $this->cookie_password, time()+(3600*24*360));
				$this->authenticated_user = $this->cookie_username;
			}
		}
	}

	// Log the user in.
	public function Login($arg_user, $arg_pass) {
		global $dbobj;

		// Get user record.
		$user_ar = $dbobj->GetResultsAsNestedArray("SELECT * FROM mr_useraccount WHERE username = " . ValToSQL_str($arg_user), 1);
		$this->user_r = $user_ar[0];

		// Compare supplied & stored passwords.
		//if (!$this->IsPlainTextPasswordCorrect($arg_pass, $this->user_r['password'], $this->user_r['passwordSalt'])) {
		$enc_password = sha1($arg_pass . $this->user_r['passwordSalt']);
		if ($enc_password !== $this->user_r['password']) {
			$this->error_string = "Username or password are incorrect.";
			return false;
		}
	
		//$_SESSION['auth_user'] = $arg_user;
		setcookie("user", $arg_user . " " . $enc_password, time()+(3600*24*360));
		$this->authenticated_user = $arg_user;

		// Update last-login.
		$dbobj->SendQuery("UPDATE mr_useraccount SET lastLoginDate = '".date("Y-m-d", time())."' WHERE username = ".ValToSQL_str($arg_user)."");

		return true;
	}

	public function LoginNoPassword($arg_user) {
		// DISABLED FOR NOW.
		//$_SESSION['auth_user'] = $arg_user;
	}
	
	// Logout user.
	public function Logout() {
		//$_SESSION['auth_user'] = '';
		setcookie("user", "x", time()-(3600*24));
		$this->authenticated_user = "";
	}
	
	
	// Return the logged-in user name.
	public function AuthenticatedUser() {
		//return $_SESSION['auth_user'];
		return $this->authenticated_user . "";
	}
	

	public function CreateUser($username, $password_plain) {
		global $dbobj;
		
		$username = trim($username);
		$password_plain = trim($password_plain);

		if (empty($username) || empty($password_plain)) {
			$this->error_string = "Username or password is empty.";
			return false;
		}

		if (!preg_match('/^[a-zA-Z0-9\_.]+$/i', $username)) {
			$this->error_string = "Usernames can only use the characters a-z, 0-9, underscore, and period.";
			return false;
		}

		$passwordSalt = $this->GetRandomString(4);
		$password_enc = sha1($password_plain.$passwordSalt);

		// Add user record.
		$dbobj->SendQuery("INSERT INTO mr_useraccount (username, password, passwordSalt, addedDateTime, lastLoginDate, addedByIP, email) VALUES (" . ValToSQL_str($username) . ", " . ValToSQL_str($password_enc) . ", " . ValToSQL_str($passwordSalt) . ", '" . date("Y-m-d", time()) . "', '" . date("Y-m-d", time()) . "', '" . $_SERVER['REMOTE_ADDR'] . "', '')");
		
		return true;
	}

	public function SetPassword($username, $password_plain) {
		global $dbobj;
		
		$username = trim($username);
		$password_plain = trim($password_plain);

		if (empty($password_plain)) {
			return false;
		}

		$passwordSalt = $this->GetRandomString(4);
		$password_enc = sha1($password_plain.$passwordSalt);

		// Update user record.
		$dbobj->SendQuery("UPDATE mr_useraccount SET password = ".ValToSQL_str($password_enc).", passwordSalt = ".ValToSQL_str($passwordSalt)." WHERE username = ".ValToSQL_str($username)."");
		
		return true;
	}


	public function UpdateUserIcon($username, $temp_icon_path) {
		global $dbobj;

		$dest_path = "" . strtolower($username) . ".jpg";
		$dest_abs_path = $_SERVER['DOCUMENT_ROOT'] . "/" . SiteConst('storage_path') . "/usericons/" . $dest_path;

		// Get src_img.
		// Note: assumes file is JPEG.
		//echo $temp_icon_path;
		if (!$src_img = imagecreatefromjpeg($temp_icon_path)) {
			echo "Error opening Image file.";
			exit();
		}

		// Clip source image into a square.
		$clip_w_by = max(0, imagesx($src_img) - imagesy($src_img));
		$clip_h_by = max(0, imagesy($src_img) - imagesx($src_img));
		$src_min_dim = min(imagesx($src_img), imagesy($src_img));
		$src_img2 = imagecreatetruecolor($src_min_dim, $src_min_dim);
		imagecopy($src_img2, $src_img, 0, 0, round($clip_w_by/2), round($clip_h_by/2), $src_min_dim, $src_min_dim);
		$src_img = $src_img2;

		// Set dest_h, dest_h
		$source_w = imagesx($src_img);
		$source_h = imagesy($src_img);
		if ($source_w < 256) {
			$dest_w = $source_w;
			$dest_h = $source_h;
		}
		else {
			$dest_w = 256;
			$dest_h = 256;
		}

		// Initialize $dst_img
		$dst_img = imagecreatetruecolor($dest_w, $dest_h);

		imagecopyresampled($dst_img, $src_img, 0, 0, 0, 0, $dest_w, $dest_h, $source_w, $source_h);

		if (!file_exists(dirname($dest_abs_path)))
			mkdir(dirname($dest_abs_path) . "/", 0777, true);
		imagejpeg($dst_img, $dest_abs_path);

		// Change the file permissions on the new file.
		// (necessary?)
		//chmod($dest_path, 0644);

		// Set userIconPath in database.
		$dbobj->SendQuery("UPDATE mr_useraccount SET userIconPath = " . ValToSQL_str($dest_path) . " WHERE username = " . ValToSQL_str($username) . "");
	}


	// See if the logged in account can use a given context.
	public function IsContextAllowed ($context_name) {
		// DISABLED FOR NOW.
		return false;

		global $dbobj;
	
		if ($dbobj->GetFirstCell("SELECT COUNT(*) FROM contextAccount WHERE username = '" . $this->AuthenticatedAccount() . "' AND contextName = '" . $context_name . "';")) {
			return true;
		}
		else {
			return false;
		}
	}

	// Get array of users in a given context.
	public function GetUsernamesInContext($context_name) {
		// DISABLED FOR NOW.
		return false;

		$user_ar = $dbobj->GetResultsAsNestedArray("SELECT * FROM contextAccount WHERE contextName = ".ValToSQL_str($context_name)." ORDER BY username", 5000);

		$output_array = array();
		foreach ($user_ar as $user_r) {
			array_push($output_array, $user_r['username']);
		}

		return $output_array;
	}


	private function IsPlainTextPasswordCorrect($password_try, $password_db, $passwordSalt_db) {
		//echo "<p>1.".sha1(trim($password_try.$passwordSalt_db));
		//echo "<p>2.".$password_db;
		if (sha1(trim($password_try.$passwordSalt_db)) == $password_db)
			return true;
		else
			return false;
	}

	// Random password salt.
	private function GetRandomString($length) {

		// start with a blank password
		$output = "";
		// define possible characters
		$possible = "23456789abcdefghjkmnpqrstuvwxyz";

		// Add random characters to $output until $length is reached
		$i = 0;
		while ($i < $length) {
			// pick a random character from the possible ones
			$char = substr($possible, mt_rand(0, strlen($possible)-1), 1);
			$output .= $char;
			$i++;
		}
		return $output;
	}


	public static function AccountNavHtml() {
		global $auth;

		if ($auth->AuthenticatedUser() != "") {
			return "<b>" . $auth->AuthenticatedUser() . "</b> | <a href='user_settings.php'>settings</a> | <a href='login.php?logout=on&amp;redirect_to=" . $_SERVER['PHP_SELF'] . "?" . $_SERVER['QUERY_STRING'] . "'>logout</a>";
		}
		else {
			return "<a href='login.php?redirect_to=" . $_SERVER['PHP_SELF'] . "?" . $_SERVER['QUERY_STRING'] . "'>login</a> | <a href='createuser1.php'>create account</a>";
		}
	}

}


?>